package com.common.utils.httpclient;

import com.common.utils.domain.AjaxResult;
import com.common.utils.excel.additionalclass.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 通用httpclient类实现外部接口统一管理
 * author zengliang
 */
public class HttpClientUtil {

    /**
     * 通用 httpClient post 1.0
     * @param url
     * @param map
     * @return
     */
    public AjaxResult httpPost(String url, Map<Object, Object> map, String accesstoken) {
        String datajson = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //请求参数
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            if(map != null){
                for (Map.Entry<Object, Object> hentity : map.entrySet()) {
                    String name = hentity.getKey()+"";
                    String value = hentity.getValue()+"";
                    if(!StringUtils.isEmpty(value)){
                        parameters.add(new BasicNameValuePair(name,value));
                    }
                }
            }
            if(parameters.size() > 0){
                HttpEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
                httpost.setEntity(formEntity);
            }
            if(!StringUtils.isEmpty(accesstoken)){
                httpost.addHeader("ACCESSTOKEN",accesstoken);
            }

            response = client.execute(httpost);
            datajson = EntityUtils.toString(response.getEntity(),"UTF-8");
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                HttpEntity entity = response.getEntity();
                return AjaxResult.success(datajson);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(datajson);
        }
        return null;
    }

    /**
     * 通用 httpClient rawpost 1.0
     * @param url
     * @param params
     * @param accesstoken
     * @return
     */
    public AjaxResult httpRawPost(String url,String params,String accesstoken ){
        String datajson = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //请求参数
            StringEntity stringEntity = new StringEntity(params);
            if(!StringUtils.isEmpty(accesstoken)){
                httpost.addHeader("ACCESSTOKEN",accesstoken);
            }
            httpost.setEntity(stringEntity);
            response = client.execute(httpost);
            datajson = EntityUtils.toString(response.getEntity(),"UTF-8");
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                HttpEntity entity = response.getEntity();
                return AjaxResult.success(datajson);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(datajson);
        }
        return null;
    }

    /**
     * 通用 httpClient get 1.0
     * @param url
     * @param map
     * @return
     */
    public AjaxResult httpGet(String url,Map<Object,Object> map,String accesstoken){
        String datajson = "";
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            //拼接请求参数
            StringBuilder postData = new StringBuilder();
            if(map != null){
                for (Map.Entry<Object, Object> hentity : map.entrySet()) {
                    if (postData.length() != 0) {
                        postData.append('&');
                    }
                    postData.append(hentity.getKey());
                    postData.append('=');
                    postData.append(hentity.getValue());
                }
            }
           /* if(!StringUtils.isEmpty(postData)){
                url = url + "?" + postData;
            }*/
            HttpGet httpget = new HttpGet(url);
            if(!StringUtils.isEmpty(accesstoken)){
               httpget.addHeader("ACCESSTOKEN",accesstoken);
            }
            CloseableHttpResponse response = null;
            response = client.execute(httpget);
            datajson = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                HttpEntity entity = response.getEntity();
                return AjaxResult.success(datajson);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(datajson);
        }
        return null;
    }


    /**
     * 通用 httpClient post 1.0 可以屏蔽证书
     * @param url
     * @param map
     * @return
     */
    public AjaxResult httpPost(String url, Map<Object, Object> map, String accesstoken,Boolean isEnableSSL) {
        String datajson = "";
        CloseableHttpClient client = HttpClients.createDefault();
        if(isEnableSSL == true){
            enableSSL(client);
        }
        HttpPost httpost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //请求参数
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            if(map != null){
                for (Map.Entry<Object, Object> hentity : map.entrySet()) {
                    String name = hentity.getKey()+"";
                    String value = hentity.getValue()+"";
                    if(!StringUtils.isEmpty(value)){
                        parameters.add(new BasicNameValuePair(name,value));
                    }
                }
            }
            if(parameters.size() > 0){
                HttpEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
                httpost.setEntity(formEntity);
            }
            if(!StringUtils.isEmpty(accesstoken)){
                httpost.addHeader("ACCESSTOKEN",accesstoken);
            }

            response = client.execute(httpost);
            datajson = EntityUtils.toString(response.getEntity(),"UTF-8");
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                HttpEntity entity = response.getEntity();
                return AjaxResult.success(datajson);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(datajson);
        }
        return null;
    }

    /**
     * 通用 httpClient get 1.0 可以屏蔽证书
     * @param url
     * @param map
     * @return
     */
    public AjaxResult httpGet(String url,Map<Object,Object> map,String accesstoken,Boolean isEnableSSL){
        String datajson = "";
        CloseableHttpClient client = HttpClients.createDefault();
        if(isEnableSSL == true){
            enableSSL(client);
        }
        try {
            //拼接请求参数
            StringBuilder postData = new StringBuilder();
            if(map != null){
                for (Map.Entry<Object, Object> hentity : map.entrySet()) {
                    if (postData.length() != 0) {
                        postData.append('&');
                    }
                    postData.append(hentity.getKey());
                    postData.append('=');
                    postData.append(hentity.getValue());
                }
            }
           /* if(!StringUtils.isEmpty(postData)){
                url = url + "?" + postData;
            }*/
            HttpGet httpget = new HttpGet(url);
            if(!StringUtils.isEmpty(accesstoken)){
                httpget.addHeader("ACCESSTOKEN",accesstoken);
            }
            CloseableHttpResponse response = null;
            response = client.execute(httpget);
            datajson = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                HttpEntity entity = response.getEntity();
                return AjaxResult.success(datajson);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(datajson);
        }
        return null;
    }

    /**
     * 屏蔽https证书校验
     * @param httpclient
     */
    public static void enableSSL(CloseableHttpClient httpclient) {
        // 调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{truseAllManager}, null);

            @SuppressWarnings("deprecation")
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static TrustManager truseAllManager = new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }
    };
}